package com.example.mybaseapp.widget

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.ViewConfiguration
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.Scroller
import androidx.appcompat.widget.AppCompatTextView
import kotlin.math.abs


/**
 * 滑动TextView
 * 实现触摸滑动和防守后的惯性滑动
 */
class ScrollerTextView:AppCompatTextView {
    private var mScroller: Scroller
    private var mVelocityTracker: VelocityTracker? = null
    private var mLastY: Int = 0
    private var contentHeight = 0
    private var maxY = 0
    init {

        mScroller = Scroller(context, AccelerateDecelerateInterpolator())

    }

    constructor(context: Context) : super(context) {
        // 构造函数处理
        initView()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        // 构造函数处理，处理从 XML 布局文件中传入的属性
        initAttars(attrs)
        initView()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        // 构造函数处理，处理从 XML 布局文件中传入的属性和样式
        initAttars(attrs)
        initView()
    }

    private fun initAttars(attrs: AttributeSet) {

    }

    private fun initView() {

    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // 初始化时计算内容高度和最大滚动位置
        contentHeight = computeVerticalScrollRange()
        maxY = contentHeight - height
        Log.d("Fire", "maxY: $maxY")
    }
    override fun onAttachedToWindow() {
        super.onAttachedToWindow()

    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain()
        }
        mVelocityTracker?.addMovement(event)
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                if (!mScroller.isFinished) {
                    mScroller.abortAnimation()
                }
                mLastY = event.y.toInt()
                return true
            }

            MotionEvent.ACTION_MOVE -> {  // Handle dragging/moving here
                val deltaY = event.y.toInt() - mLastY
                val newScrollY = scrollY - deltaY
                if (newScrollY < 0 || newScrollY > maxY) { // 到达顶部或底部边界
                    return true
                }

                scrollBy(0, -deltaY) // 反向滚动，实现滑动效果
                mLastY = event.y.toInt()
                return true
            }

            MotionEvent.ACTION_UP -> {
                mVelocityTracker?.computeCurrentVelocity(1000) // 毫秒为单位
                val initialVelocityY = mVelocityTracker?.yVelocity?.toInt() ?: 0

                if (abs(initialVelocityY.toDouble()) > ViewConfiguration.get(
                        context
                    ).scaledMinimumFlingVelocity
                ) {
                    flingY(-initialVelocityY)
                }

                mVelocityTracker?.recycle()
                mVelocityTracker = null
                return true
            }

            MotionEvent.ACTION_CANCEL -> {
                mVelocityTracker?.recycle()
                mVelocityTracker = null
                return true
            }
        }
        return super.onTouchEvent(event)
    }

    private fun flingX(velocityX: Int) {
        val maxX = computeHorizontalScrollRange() - width
        mScroller.fling(scrollX, 0, velocityX, 0, 0, maxX, 0, 0)
        postInvalidateOnAnimation()
    }

    private fun flingY(velocityY: Int) {
        val maxY = computeVerticalScrollRange() - height
        mScroller.fling(0, scrollY, 0, velocityY, 0, 0, 0, maxY)
        postInvalidateOnAnimation()
    }

    override fun computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.currX, mScroller.currY)
            postInvalidate()
            Log.d("Fire", "computeScroll: true")
        }else{
            Log.d("TAG", "computeScroll: 滑动结束")
        }
    }

}